//
//  WSChapterController.m
//  CharonTVProject
//
//  Created by karong on 2023/8/8.
//

#import "WSChapterController.h"
#import "WSChapterCell.h"
#import "WSChapterTitleCell.h"
#import "WSVideoDetail.h"
#import "WSFavoritesRequest.h"
#import "WSPlayerRequest.h"
#import "UIButton+ImageAlign.h"

@interface WSChapterController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, WSChapterCellDelegate>
@property (weak, nonatomic) IBOutlet UIView *mainView;
@property (weak, nonatomic) IBOutlet UICollectionView *titleListView;
@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalChapterCountLabel;
@property (weak, nonatomic) IBOutlet UIButton *collectBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *mainViewBottom;
@property (nonatomic, strong) NSArray * dataArray;
@property (nonatomic, assign) NSInteger selectPage;

@end

@implementation WSChapterController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layoutMainView];
    [self.collectBtn setButtonImageTitleStyle:(WSButtonImageTitleStyleLeft) padding:9.5];
    [self layoutCollectStatus];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.mainViewBottom.constant = 0;
        [self.view uploadLayout];
    });
}

- (void)layoutMainView {
    if (self.charonTV_videoDetail) {
        for (WSVideo * video in self.charonTV_videoDetail.chapter_list) {
            if (video.id == self.charonTV_video.id) {
                video.isSelected = YES;
            }
            else {
                video.isSelected = NO;
            }
        }
        self.dataArray = self.charonTV_videoDetail.chapter_list;
        [self.titleListView reloadData];
        [self.listView reloadData];
        self.titleLabel.text = self.charonTV_videoDetail.title;
        self.totalChapterCountLabel.text = WSSF(@"%@%ld%@", APPLocalized(@"更新至"),self.charonTV_videoDetail.total_chapter,APPLocalized(@"集"));
    }
    else {
        self.titleLabel.text = WSEmptyStr(self.charonTV_video.tv_title);
        [self loadTVDetailcharonTV_Request];
    }
}

- (void)layoutCollectStatus {
    self.collectBtn.selected = self.charonTV_videoDetail.is_collect;
}

- (void)loadTVDetailcharonTV_Request {
    WeakSelf
    [WSPlayerRequest loadcharonTV_shotTVDetailWithID:self.charonTV_video.tv_id success:^(id obj) {
        weakSelf.charonTV_videoDetail = obj;
        [weakSelf layoutMainView];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)addFavoritecharonTV_Request {
    [WSToast loading];
    [WSFavoritesRequest addcharonTV_FavoriteWithChapterId:self.charonTV_video.id tv_id:self.charonTV_video.tv_id success:^{
        [WSToast dismiss];
        self.charonTV_videoDetail.is_collect = YES;
        [WSToast simple:@"收藏成功"];
        [self layoutCollectStatus];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)delFavoritecharonTV_Request {
    [WSToast loading];
    [WSFavoritesRequest delcharonTV_FavoriteWithTVIds:@[self.charonTV_video] success:^{
        [WSToast dismiss];
        self.charonTV_videoDetail.is_collect = NO;
        [WSToast simple:@"已取消收藏"];
        [self layoutCollectStatus];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {

    }];
}

- (IBAction)closeAction:(id)sender {
    [self dismiss];
}

- (IBAction)collectAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (self.charonTV_videoDetail.is_collect) {
        [self delFavoritecharonTV_Request];
    }
    else {
        [self addFavoritecharonTV_Request];
    }
}
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    if (scrollView == self.listView) {
        CGFloat x = scrollView.contentOffset.x / WSScreenWidth;
        self.selectPage = x;
        [self.titleListView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:x inSection:0] atScrollPosition:(UICollectionViewScrollPositionCenteredHorizontally) animated:YES];
        [self.titleListView reloadData];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.listView) {
        CGFloat x = scrollView.contentOffset.x / WSScreenWidth;
        self.selectPage = x;
        [self.titleListView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:x inSection:0] atScrollPosition:(UICollectionViewScrollPositionCenteredHorizontally) animated:YES];
        [self.titleListView reloadData];
    }
}

#pragma mark UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSInteger count = self.charonTV_videoDetail.totalPage;
    return count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.titleListView) {
        WSChapterTitleCell * chapterTitleCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WSChapterTitleCell" forIndexPath:indexPath];
        [chapterTitleCell setDataWithObject:[self.charonTV_videoDetail  pageTitle:indexPath.row] select:self.selectPage == indexPath.row];
        return chapterTitleCell;
    }
    else {
        WSChapterCell * chapterCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WSChapterCell" forIndexPath:indexPath];
        chapterCell.delegate = self;
        [chapterCell setDataWithObject:[self.charonTV_videoDetail videoArrayWithPage:indexPath.row]];
        return chapterCell;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeZero;
    if (collectionView == self.titleListView) {
        CGFloat width = [[self.charonTV_videoDetail  pageTitle:indexPath.row] boundingRectWithSize:CGSizeMake(MAXFLOAT, 0.0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:16]} context:nil].size.width;
        size.width = width;
        size.height = 50;
    }
    else {
        size.width = WSScreenWidth;
        size.height = 67 * 3 + 12 + 12;
    }
    return size;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    UIEdgeInsets inset = UIEdgeInsetsZero;
    if (collectionView == self.titleListView) {
        inset.left = 12;
        inset.right = 12;
    }
    return inset;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.titleListView) {
        self.selectPage = indexPath.row;
        [self.listView scrollToItemAtIndexPath:indexPath atScrollPosition:(UICollectionViewScrollPositionCenteredVertically) animated:YES];
        [self.titleListView reloadData];
    }
}
#pragma mark WSChapterCellDelegate
- (void)chapterCellDidSelectItemWithObject:(id)object {
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.charonTV_selectHandle) {
            self.charonTV_selectHandle(object);
        }
    }];
}

- (void)setCharonTV_video:(WSVideo *)charonTV_video {
    _charonTV_video = charonTV_video;
    self.selectPage = (charonTV_video.sort - 1) / 18;
}
@end
